package services

import (
	"gorm.io/gorm"
	"social-contact/global"
	"social-contact/internal/models/dao"
)

func CreateUser(user dao.User) error {
	return global.Db.Create(&user).Error
}

func GetUserInfo(name string) (user dao.User, err error) {
	err = global.Db.Where("name = ?", name).First(&user).Error
	return
}

func ReleaseDynamic(dynamic dao.Dynamic) error {
	return global.Db.Create(&dynamic).Error
}

func List(likes string, page, pageSize int) (list []dao.Dynamic, err error) {
	err = global.Db.Where("likes like ?", "%"+likes+"%").Order("likes desc").Scopes(Paginate(page, pageSize)).Find(&list).Error
	return list, err
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func SubscribeFollow(follow dao.Follow) error {
	return global.Db.Create(&follow).Error
}

func CreateGroup(group dao.Group) error {
	return global.Db.Create(&group).Error
}

func AdministrationMember(member dao.Member) error {
	return global.Db.Create(&member).Error
}

func Del(position string) error {
	var user dao.Member
	return global.Db.Where("position = ?", position).Delete(&user).Error
}
